package org.hong.samples.service.imp;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Workbook;
import org.hong.samples.dao.UserDAO;
import org.hong.samples.model.ExamUserRole;
import org.hong.samples.model.UserJDBC;
import org.hong.samples.model.Pager.PagerModel;
import org.hong.samples.model.VO.UserJDBCVO;
import org.hong.samples.service.UserService;
import org.hong.samples.util.ExcelUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImp implements UserService{

	@Autowired
	private UserDAO userDAO;
	
	@Override
	public List<UserJDBC> findAllUsers() {
		// TODO Auto-generated method stub
		return userDAO.findAllUsers();
	}

	@Override
	public UserJDBCVO getUserVOById(String id) {
		// TODO Auto-generated method stub
		UserJDBC userJDBC = userDAO.getUserById(id);
		if(userJDBC != null){
			UserJDBCVO userJDBCVO = new UserJDBCVO();
			BeanUtils.copyProperties(userJDBC, userJDBCVO);
			return userJDBCVO;
		}
		return null;
	}
	
	@Override
	public UserJDBC getUserById(String id) {
		return userDAO.getUserById(id);
	}
	

	@Override
	public void editUser(UserJDBC user) throws Exception {
		// TODO Auto-generated method stub
		userDAO.editUser(user);
	}

	@Override
	public void saveUser(UserJDBC user) throws Exception {
		// TODO Auto-generated method stub
		userDAO.saveUser(user);
	}

	@Override
	public void deleteUser(String id) throws Exception {
		// TODO Auto-generated method stub
		userDAO.deleteUser(id);
	}

	@Override
	public PagerModel<UserJDBCVO> findAllByPage() {
		// TODO Auto-generated method stub
		return userDAO.findAllByPage();
	}

	@Override
	public void saveStudentByExcel(InputStream inputStream, String postfix) {
		Workbook wk = ExcelUtils.openWorkbook(inputStream,postfix);
		List<UserJDBCVO> allExcelUser = ExcelUtils.getStudentListByExcel(wk);
		List<UserJDBC> entities =  new ArrayList<UserJDBC>();
		if(allExcelUser != null){
			UserJDBC entity = null;
			for(int i = 0;i<allExcelUser.size();i++){
				entity= new UserJDBC();
				BeanUtils.copyProperties(allExcelUser.get(i), entity);
				entities.add(entity);
			}
		}
		userDAO.saveOrUpdate(entities);
	}

	@Override
	public void updateUserLoginFailCount(String userId,String count) {
		// TODO Auto-generated method stub
		userDAO.updateUserLoginFailCount(userId, count);
	}

	@Override
	public void updateUserLastLockTime(String userId, String locktime) {
		// TODO Auto-generated method stub
		userDAO.updateUserLastLockTime(userId, locktime);
	}

	@Override
	public ExamUserRole getRoleId(String id) {
		// TODO Auto-generated method stub
		return userDAO.getRoleId(id);
	}


}
